import XLSX from 'xlsx'

/**
 * @description: 导入excel文件并返回数据
 * @param {function} 回调函数参数data,dataRef,一个是数据，一个是exce表单的索引
 * @return:
 */
function importExcel(callback) {
  var inputObj = document.createElement('input')
  inputObj.setAttribute('id', 'file')
  inputObj.setAttribute('type', 'file')
  inputObj.setAttribute('name', 'file')
  inputObj.setAttribute('style', 'visibility:hidden')
  inputObj.setAttribute('accept', '.xlsx,.xls,.csv')
  inputObj.addEventListener('change', (evt) => {
    const files = evt.target.files
    if (files && files[0]) {
      _file(files[0], (data, dataRef) => {
        callback(data, dataRef)
      })
    }
  })
  document.body.appendChild(inputObj)
  inputObj.value
  inputObj.click()
}

/**
 * @description: 处理文件
 * @param {Object} file 文件对象
 * @param {function} callback 回调函数
 * @return:
 */
function _file(file, callback) {
  const make_cols = refstr => Array(XLSX.utils.decode_range(refstr).e.c + 1).fill(0).map((x, i) => ({
    name: XLSX.utils.encode_col(i),
    key: i
  }))

  /* Boilerplate to set up FileReader */
  const reader = new FileReader()
  reader.onload = (e) => {
    /* Parse data */
    const bstr = e.target.result
    const wb = XLSX.read(bstr, {
      type: 'binary'
    })
    /* Get first worksheet */
    const wsname = wb.SheetNames[0]
    const ws = wb.Sheets[wsname]
    /* Convert array of arrays */
    const data = XLSX.utils.sheet_to_json(ws, {
      header: 1
    })
    const list = []
    let obj = {}
    for (const key in data) {
      if (key === '0') {
        for (const key1 in character) {
          for (const key2 in data[key]) {
            if (key1 === data[key][key2]) {
              data[key][key2] = character[key1].text
            }
          }
        }
      } else {
        for (const key3 in data[key]) {
          obj[data['0'][key3]] = data[key][key3]
        }
        list.push(obj)
        obj = {}
      }
    }
    /* Update state */
    callback(list, make_cols(ws['!ref']))
  }
  reader.readAsBinaryString(file)
}

const character = {
  序号: {
    text: 'numberNo',
    type: String
  },
  企业名称: {
    text: 'entName',
    type: String
  },
  发展评分: {
    text: 'targetScore',
    type: String
  },
  创新型评分: {
    text: 'innovateScore',
    type: String
  },
  创新型评测: {
    text: 'innovationContent',
    type: String
  },
  专精特新评分: {
    text: 'refinementScore',
    type: String
  },
  专精特新评测: {
    text: 'refinementContent',
    type: String
  },
  小巨人评测: {
    text: 'giantContent',
    type: String
  }
}

export default {
  importExcel
}
